import json
import time

import common.dataBase as db

import requests


def get_date(t):
    sss = time.time() + 3600 * 24 * t
    return time.strftime('%Y-%m-%d', time.localtime(sss))


def get_data(pid, cid, info, sign, url):
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36 Edg/100.0.1185.36',
        'x-client-extend': 'eyJkYXRlIjoiMjAyMi0wNC0xMiAxOToxMTozMCArMDg6MDAiLCJpZCI6IjAzZGI0YzdhYjczZTQyZTAxZGI2MmRlY2ZlMDYxYTM5IiwiaWRTY29yZSI6MC42fQ==',
        'x-client-id': cid,
        'referer': 'https://www.lvdingjia.com/',
        'x-client-info': info,
        'x-client-sign': sign,
        'origin': 'https://www.lvdingjia.com',
        'content-type': 'application/json'
    }
    s = get_date(-2) + 'T16:00:00.000Z'
    e = get_date(-1) + 'T16:00:00.000Z'
    param = json.dumps(
        {
            "type": 0,
            "show": {
                "dateStart": s,
                "dateEnd": e
            },
            "parentId": pid
        })
    print(param)
    response = requests.post(url, headers=headers, data=param)
    print(response.text)
    json_data = json.loads(response.text)['data']['data'][0]
    return json_data['avg'], json_data['show'][:10]


def app(pid, idd, info, sign, name):
    url = 'https://api.cndl.vip/api/app/web/market/price'
    d = get_data(pid, idd, info, sign, url)
    insert_sql = f'INSERT INTO mat_price VALUES (null, "{name}", "{d[0]}","", "{d[1]}", "{url}")'
    db.save([insert_sql])


if __name__ == "__main__":
    app("01ecbbfc-f000-92ea-590a-f579f6363f31",
        "61a53456-637a-b1e3-00cf-2af149513cb3",
        "66a2964fa4f9ae31d9da5979e4006314",
        "7d8f66876bf24096fc7c06e8c66446a9",
        "南储华南")
